﻿// SilverlightBridge
// Copyright (c) 2009
// by OpenLight Group
// http://openlightgroup.net/
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
//
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using SilverlightFileManager;
using System.Security.Principal;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void LoginControl_Authenticate(object sender, AuthenticateEventArgs e)
    {
        // Try to authendicate
        SilverlightFileManagerDALDataContext SilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();

        // Get allowed Login Failures
        int intAllowedLoginFailures = 5;

        var result = from ASilverlightBridgeUser in SilverlightFileManagerDALDataContext.SilverlightBridgeUsers
                     where ASilverlightBridgeUser.UserName == LoginControl.UserName
                     select ASilverlightBridgeUser;

        SilverlightBridgeUser SilverlightBridgeUser = (SilverlightBridgeUser)result.FirstOrDefault();

        if (SilverlightBridgeUser != null)
        {
            if (SilverlightBridgeUser.Password == LoginControl.Password)
            {
                if (!SilverlightBridgeUser.Active)
                {
                    LoginControl.FailureText = "Your account is not active. You cannot login until an administrator resets your account.";

                    // Log the event
                    ApplicationApplicationLog.AddToLog(SilverlightBridgeUser.UserName, "Login attempt. Account Not Active");
                }
                else if (SilverlightBridgeUser.Active)
                {
                    // Set any possible failed login attempts back to 0
                    SilverlightBridgeUser.LoginFailures = 0;
                    SilverlightFileManagerDALDataContext.SubmitChanges();

                    // Log the user into the site
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                      SilverlightBridgeUser.UserName,
                      DateTime.Now,
                      DateTime.Now.AddDays(30),
                      false,
                      SilverlightBridgeUser.Role,
                      FormsAuthentication.FormsCookiePath);

                    // Log the event
                    ApplicationApplicationLog.AddToLog(SilverlightBridgeUser.UserName, "User Logged In");

                    // Encrypt the ticket.
                    string encTicket = FormsAuthentication.Encrypt(ticket);

                    // Create the cookie.
                    Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

                    // Create an Identity object
                    FormsIdentity id = new FormsIdentity(ticket);

                    // This principal will flow throughout the request.
                    GenericPrincipal principal = new GenericPrincipal(id, null);
                    // Attach the new principal object to the current HttpContext object
                    Context.User = principal;

                    // Redirect back to original URL.
                    Response.Redirect(FormsAuthentication.GetRedirectUrl(SilverlightBridgeUser.UserName, false));
                }
            }
            else
            {
                // Bad Password
                SilverlightBridgeUser.LoginFailures++;

                // Is this user locked out?
                if (SilverlightBridgeUser.LoginFailures >= intAllowedLoginFailures)
                {
                    SilverlightBridgeUser.Active = false;
                    LoginControl.FailureText = "Your account has been locked out because of too many invalid login attempts. Please contact the administrator to have your account unlocked.";

                    // Log the event
                    ApplicationApplicationLog.AddToLog(SilverlightBridgeUser.UserName, "Account has been locked out because of too many invalid login attempts");
                }
                else
                {
                    LoginControl.FailureText = String.Format("The password entered is incorrect. You have {0} more attempts", (intAllowedLoginFailures - SilverlightBridgeUser.LoginFailures).ToString());

                    // Log the event
                    ApplicationApplicationLog.AddToLog(SilverlightBridgeUser.UserName, String.Format("The password entered is incorrect. You have {0} more attempts", (intAllowedLoginFailures - SilverlightBridgeUser.LoginFailures).ToString()));
                }

                SilverlightFileManagerDALDataContext.SubmitChanges();
            }
        }
        else
        {
            ApplicationApplicationLog.AddToLog(LoginControl.UserName, "Login attempt. Bad Username");
        }
    }
}
